<template>
  <div class="product-list">
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-if="!isEmpty"
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="props.isImmediate"
        @load="onLoad"
      >
        <van-row>
          <van-col span="12" v-for="item in list" :key="item.id">
            <product-card :product="item" />
          </van-col>
        </van-row>
      </van-list>
    </van-pull-refresh>
    <van-empty image="search" description="哦吼,没找到!" v-if="isEmpty" />
  </div>
</template>

<script setup lang="ts">
import {
  getProducts,
  getProductsByCategoryId,
  getProductsByUserId,
  searchProduct
} from '../service/product'
import { productsRes } from '../service/product/types'
import ProductCard from './product-card.vue'

const props = defineProps<{
  method: 'search' | 'category' | 'publish'
  categoryId?: number
  searchVal?: string
  isImmediate: boolean
}>()
const emit = defineEmits<{
  (e: 'getTotalCount', totalCount: number): void
}>()

const route = useRoute()
const list = ref<productsRes.Product[]>([])
const loading = ref<boolean>(false)
const finished = ref<boolean>(false)
const totalCount = ref<number>(0)
const isEmpty = ref<boolean>(false)
const refreshing = ref<boolean>(false)

const onRefresh = () => {
  finished.value = false
  loading.value = true
  onLoad()
}
const onLoad = async () => {
  if (refreshing.value) {
    list.value = []
    refreshing.value = false
  }
  if (props.method === 'category' && props.categoryId) {
    let res
    if (props.categoryId === -1) {
      res = await getProducts(list.value.length, 10)
    } else {
      res = await getProductsByCategoryId(props.categoryId, {
        offect: list.value.length,
        limit: 10
      })
    }
    list.value.push(...res.data.products)
    totalCount.value = res.data.totalCount
    loading.value = false
  }
  if (props.method === 'search' && props.searchVal) {
    isEmpty.value = false
    const res = await searchProduct(props.searchVal, {
      offect: list.value.length,
      limit: 10
    })
    list.value.push(...res.data.products)
    if (list.value.length === 0) isEmpty.value = true
    totalCount.value = res.data.totalCount
    loading.value = false
  }
  if (props.method === 'publish') {
    const userId = parseInt(route.params.id as string)
    const res = await getProductsByUserId(userId, {
      offect: list.value.length,
      limit: 10
    })
    list.value.push(...res.data.products)
    totalCount.value = res.data.totalCount
    loading.value = false
    emit('getTotalCount', res.data.totalCount)
  }
  if (list.value.length >= totalCount.value) {
    finished.value = true
  }
}
defineExpose({
  list,
  finished,
  refreshing,
  onRefresh
})
</script>

<style lang="scss" scoped>
.product-list {
  height: 100%;
  :deep(.van-pull-refresh) {
    height: 100%;
  }
}
</style>
